import {
	Inject
} from 'plugins'
import config from 'config';

@Inject('$scope', '$state', 'ui.dialog', 'ui.http', 'ui.api', 'MetaFieldService')
export class MetaFieldList {
	constructor($scope, $state, dialog, http, api, service) {
		// 设置排序字段
		var _dirs = ['asc', 'desc'];
		var sortFields = $scope.sortFields = [{
			name: 'displayName',
			value: '按显示名称',
			dir: _dirs[0]
		}, {
			name: 'fieldType',
			value: '按数据类型',
			dir: _dirs[1]
		}];
		var _sort = {
			name: sortFields[0].name
		};
		$scope.sort = _sort;

		var q = $scope.q = {};

		var loadData = $scope.loadData = function(params) {
			params = params || {};
			angular.extend(params, {
				sort: _sort.name,
				dir: _sort.dir || _dirs[0]
			})
			api.gridLoad({
				name: 'meta_fields',
				params: params,
				scope: $scope
			});
		};

		var query = $scope.query = function(resetPage) {
			if (resetPage === false || $scope.gridOptions.paginationCurrentPage == 1) {
				loadData(q);
			} else {
				api.gridReset(null, $scope);
			}
		}

		$scope.filter = function(field) {
			if (field.name == $scope.sort.name) {
				field.dir = field.dir == _dirs[0] ? _dirs[1] : _dirs[0];
				$scope.sort.dir = field.dir;
				query();
				return;
			}
			$scope.sort.name = field.name;
			$scope.sort.dir = field.dir;
			query();
		}

		$scope.gridOptions = {
			showHeader: false,
			enableRowSelection: true,
			enableRowHeaderSelection: false,
			paginationCurrentPage: api.page.pageNumber,
			// paginationPageSize: api.page.pageSize,
			paginationPageSize: 19,
			useExternalPagination: true,
			paginationTemplate: 'grid/ui-paging',
			rowClass: function(row, data) {
				if (data.id < 0) {
					row.enableSelection = false;
				}
			},
			dataView: {
				field: 'name',
				itemAddTemplate: '<div class="ui-grid-item">\
								<div class="ui-item-add" ng-click="grid.appScope.add()">\
									<div class="ui-item-add-ico">\
										<div class="ui-item-add-border">\
											<i class="ui-item-add-ico-vertical"></i>\
											<i class="ui-item-add-ico-horizontal"></i>\
										</div>\
									</div>\
									<div class="ui-item-add-text"><span class="text-inner">新建指标</span></div>\
								</div>\
							</div>',
				rowTemplate: '<div class="ui-grid-item-body">\
							<div class="data-table">\
								<dl>\
									<dt>指标名称：</dt>\
									<dd>{{grid.getRowValue(row, \'metricCode\')}}</dd>\
								</dl>\
								<dl>\
									<dt>中文名称：</dt>\
									<dd>{{grid.getRowValue(row, \'metricCn\')}}</dd>\
								</dl>\
								<dl>\
									<dt>字段长度：</dt>\
									<dd>{{grid.getRowValue(row, \'fieldLength\')}}</dd>\
								</dl>\
								<dl>\
									<dt>数据类型：</dt>\
									<dd>{{grid.appScope.getDataTypeName(grid.getRowValue(row, \'fieldType\'))}}</dd>\
								</dl>\
							</div>\
						  </div>',
				tools: [{
					icoCls: 'edit'
				}, {
					field: 'id',
					name: 'treeview',
					icoCls: 'crosshairs',
					visible: function(grid, row, id, data) {
						return id > 0;
					}
				}, {
					field: 'id',
					name: 'remove',
					icoCls: 'trash-o'
				}]
			},
			onRegisterApi: function(api) {
				$scope.api = api;
				api.pagination && api.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
					query(false);
				});
			}
		};

		$scope.dataTypes = service.dataTypes;
		$scope.formTypes = service.formTypes;
		$scope.metricTypes = service.metricTypes;
		$scope.getDataTypeName = service.getDataTypeName;

		$scope.add = function() {
			service.add().then(function() {
				query();
			});
		}
		$scope.edit = function(ev, id, data) {
			service.edit(id).then(function() {
				query(false);
			});
		}
		// $scope.treeview = function(ev, id) {
		// 	$state.go('meta.treeview', {
		// 		id: id
		// 	})
		// }
		var defaultStyle = {
			node: {
				diameter: "40",
				color: "#DFE1E3",
				"border-color": "#D4D6D7",
				"border-width": "2",
				"text-color-internal": "#000000",
				"font-size": "10"
			},
			"node.Unknown": {
				"border-color": "#D4D6D7",
				"border-width": "2",
				color: "#DFE1E3",
				diameter: "30",
				"font-size": "10",
				"text-color-internal": "#000000"
			},
			"node.Company": {
				"border-color": "#0076c6",
				"border-width": "2",
				color: "#0183fe",
				diameter: "35",
				"font-size": "10",
				"text-color-internal": "#FFFFFF",
				icon: ""
			},
			"node.Human": {
				"border-color": "#DC4717",
				"border-width": "2",
				color: "#F25A29",
				diameter: "25",
				"font-size": "10",
				"text-color-internal": "#FFFFFF",
				icon: ""
			},
			"node.Lawsuit": {
				"border-color": "#01a78a",
				"border-width": "2",
				color: "#0ac7a6",
				diameter: "65",
				"font-size": "10",
				"text-color-internal": "#FFFFFF"
			},
			"node.PhoneRecord": {
				"border-color": "#F3BA25",
				"border-width": "2",
				color: "#FCC940",
				diameter: "50",
				"font-size": "10",
				"text-color-internal": "#000000"
			},
			"node.AccountRecord": {
				"border-color": "#EB5D6C",
				"border-width": "2",
				color: "#FF6C7C",
				diameter: "65",
				"font-size": "10",
				"text-color-internal": "#FFFFFF"
			},
			"node.Dishonest": {
				"border-color": "#EB5D6C",
				"border-width": "2",
				color: "#FF6C7C",
				diameter: "65",
				"font-size": "10",
				"text-color-internal": "#FFFFFF"
			},
			relationship: {
				color: "#D4D6D7",
				"shaft-width": "1",
				"font-size": "8",
				padding: "3",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			},
			"relationship.invest": {
				"border-color": "#DC4717",
				color: "#f19d43",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			},
			"relationship.invest_c": {
				"border-color": "#DC4717",
				color: "#F25A29",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			},
			"relationship.INVEST_C": {
				"border-color": "#DC4717",
				color: "#F25A29",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			},
			"relationship.invest_h": {
				"border-color": "#DC4717",
				color: "#F25A29",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			},
			"relationship.INVEST_H": {
				"border-color": "#DC4717",
				color: "#F25A29",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			},
			"relationship.own": {
				color: "#cce198",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			},
			"relationship.OWN": {
				color: "#cce198",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			},
			"relationship.branch": {
				color: "#91abd1",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			},
			"relationship.BRANCH": {
				color: "#91abd1",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			},
			"relationship.participate": {
				"border-color": "#46A39E",
				color: "#80c2d8",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			},
			"relationship.PARTICIPATE": {
				"border-color": "#46A39E",
				color: "#80c2d8",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			},
			"relationship.involve": {
				"border-color": "#46A39E",
				color: "#6c9e81",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			},
			"relationship.INVOLVE": {
				"border-color": "#46A39E",
				color: "#6c9e81",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			},
			"relationship.transform": {
				"border-color": "#DDAA00",
				color: "#DDAA00",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			},
			"relationship.telecom": {
				"border-color": "#D4D6D7",
				color: "#30B6AF",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			},
			"relationship.relativ": {
				"border-color": "#F3BA25",
				color: "#AD62CE",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#000000"
			},
			"relationship.serve": {
				"border-color": "#9453B1",
				color: "#80c2d8",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			},
			"relationship.SERVE": {
				"border-color": "#9453B1",
				color: "#80c2d8",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			},
			"relationship.dishonest": {
				"border-color": "#EB5D6C",
				color: "#FF6C7C",
				"font-size": "8",
				padding: "3",
				"shaft-width": "2",
				"text-color-external": "#000000",
				"text-color-internal": "#FFFFFF"
			}
		};

		$scope.treeview = function(ev, id) {
			api.form({
				title: '指标立方',
				template: require('../views/form_treeview.tpl.html'),
				afterRendered: function() {
					var _scope = this;
					var nodes, edges,
						w = document.getElementById("data-view"),
						options = {
							autoResize: true,
							nodes: {
								shape: "box",
								labelHighlightBold: false,
								font: {
									size: 18,
									color: "#ffffff"
								},
								borderWidth: 2,
								scaling: {
									label: {
										min: 5,
										max: 18
									}
								}
							},
							edges: {
								// alwaysShow: false,
								dashes: false,
								labelHighlightBold: false,
								physics: false,
								arrows: {
									to: {
										enabled: true,
										scaleFactor: 1
									},
									middle: {
										enabled: false,
										scaleFactor: 1
									},
									from: {
										enabled: false,
										scaleFactor: 1
									}
								},
								color: {
									color: "#aaaaaa",
									hover: "#aaaaaa",
									highlight: "#848484",
									opacity: .8
								},
								font: {
									color: "#efefef",
									size: 3,
									strokeWidth: 0
								},
								smooth: {
									enabled: false,
									type: "dynamic",
									roundness: 1
								},
								length: 80
							},
							interaction: {
								hover: true,
								zoomView: true
							},
							physics: {
								enabled: false
							}
						},
						toMap = function(data) {
							var result = {};
							for (var i = 0; i < data.length; i++) result[data[i].id] = data[i];
							return result
						};

					nodes = new vis.DataSet([]);
					edges = new vis.DataSet([]);
					var network = new vis.Network(w, {
						nodes: nodes,
						edges: edges
					}, options);

					_scope.dataloading = false;
					_scope.viewloading = false;
					var render = function(params, always) {
						_scope.dataloading = true;
						return http.post({
							name: 'meta_treeview_data',
							params: params,
							success: function(data) {
								_scope.viewloading = true;

								var _nodes = data.nodes,
									_edges = data.relationships,
									r = toMap(_nodes);
								var i;
								for (i = 0; i < _edges.length; i++) {
									_edges[i].source = r[_edges[i].startNode];
									_edges[i].target = r[_edges[i].endNode]
								}
								var edges_data = [];
								for (i = 0; i < _edges.length; i++) {
									var edge = _edges[i],
										_data = {};
									_data.title = edge.properties.labels[0];
									_data.label = edge.properties.labels[0];
									_data.from = edge.startNode;
									_data.to = edge.endNode;
									_data.arrows = "to";
									_data.font = {
										align: "middle",
										color: "#000",
										strokeWidth: 0,
										strokeColor: "#009bae",
										background: "#fff",
										size: 12,
										face: "arial"
									};
									var type = _edges[i].type;

									type = type ? "relationship." + type : "relationship";
									_data.type = type;
									defaultStyle[type] || (defaultStyle[type] = defaultStyle["relationship"]);
									_data.color = {
										color: defaultStyle[type].color,
										highlight: defaultStyle[type].color,
										hover: defaultStyle[type].color
									};
									edges_data.push(_data)
								}
								var draw = function() {
										var nodes_data = [];
										for (var i = 0; i < _nodes.length; i++) {
											var node = _nodes[i],
												type = node.labels[0] ? "node." + node.labels[0] : "node";
											defaultStyle[type] || (defaultStyle[type] = defaultStyle["node"]);
											nodes_data.push({
												label: node.properties.name,
												title: node.properties.name,
												id: node.id,
												color: defaultStyle[type].color,
												x: node.x,
												y: node.y,
												type: type,
												size: 1 * defaultStyle[type].diameter,
												font: {
													size: 12,
													color: "#ffffff"
												}
											})
										}
										nodes = new vis.DataSet(nodes_data);
										edges = new vis.DataSet(edges_data);
										var _data = {
											nodes: nodes,
											edges: edges
										};
										network.setData(_data)
									},
									graph = function(force, callback) {
										var _tick, r, n, a, getTime;
										_tick = force.tick;
										force.tick = function() {
											var r, l;
											for (r = getTime(), l = a; l-- && getTime() - r < n;)
												if (_tick()) {
													a = 2;
													return true;
												}
											if (force.alpha() < .02) {
												force.stop();
												callback && callback();
											}
										}
										return a = 100, r = 60, n = 1e3 / r, getTime = angular.isDefined(window.performance) && angular.isFunction(window.performance.now) ? function() {
											return window.performance.now()
										} : function() {
											return Date.now()
										}
									},
									force = d3.layout.force().linkDistance(function(e) {
										return 200
									}).charge(-2e3).nodes(_nodes).links(_edges);
								graph(force, function() {
									draw();
									_scope.viewloading = false;
									if (!_scope.$$phase) {
										// _scope.$apply();
										_scope.$digest();
									}
								});
								force.start()
							}
						}).finally(function() {
							_scope.dataloading = false;
						});
					}

					render({
						id: id
					});
				},
				config: {
					// windowClass: 'x-window x-window-selection',
					width: '70%',
					resolve: {
						scripts: ['lazyScript', function(lazyScript) {
							return lazyScript.register([
								'assets/js/vis.min.js',
								'assets/js/d3.min.js'
							]);
						}]
					}
				}
			});
		}
		$scope.remove = function(ev, id) {
			dialog.confirm('确定要删除当前字段吗？').result.then(function(r) {
				if (r) {
					http.post({
						name: 'meta_field_remove',
						params: {
							id: id
						},
						success: function() {
							query(false);
						}
					})
				}
			});
		}

		query();
	}
}